package com.liujun.spring4x.demo.web;

import com.google.gson.Gson;
import com.liujun.spring4x.demo.domain.User;
import com.liujun.spring4x.demo.service.UserService;
import com.liujun.spring4x.demo.web.vo.LoginCommand;
import com.liujun.spring4x.demo.web.vo.restful.MonitorRestFul;
import com.liujun.spring4x.demo.web.vo.restful.ResultInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * 进行登录的control流程控制
 *
 * @author liujun
 * @version 1.0
 * @date 2018-08-05 21:29:00
 */
@Controller
public class LoginController {

  /** 用户信息 */
  private UserService userService;

  private Gson gson = new Gson();

  @RequestMapping(value = "/index.html")
  public String loginPage() {
    return "login";
  }

  /**
   * 登录的控制处理
   *
   * @param request 请求的对象
   * @param logincmd 登录的参数对象
   * @return 视图对象
   */
  @RequestMapping(value = "/loginCheck.html")
  public ModelAndView loginCheck(HttpServletRequest request, LoginCommand logincmd) {
    boolean validUser =
        this.userService.hasMatchUser(logincmd.getUserName(), logincmd.getPassword());
    if (!validUser) {
      return new ModelAndView("login", "error", "用户名或者密码错误。");
    } else {
      User user = userService.findUserByUserName(logincmd.getUserName());
      user.setLastIp(request.getLocalAddr());
      user.setLastVisit(new Date());
      // 进行登录流程
      userService.loginSuccess(user);
      // 写入session中
      request.getSession().setAttribute("user", user);

      return new ModelAndView("main");
    }
  }

  /**
   * 登录的控制处理
   *
   * @return 视图对象
   */
  @RequestMapping(
      value = "/resultMonitor.html",
      method = RequestMethod.POST,
      consumes = "application/json")
  @ResponseBody
  public ResultInfo restfulMonitor(@RequestBody List<MonitorRestFul> msg) {
    System.out.println(msg);

    ResultInfo info = new ResultInfo();
    info.setMessage("success");
    info.setResultCode(200);
    info.setSuccess(true);
    info.setTimestamp(System.currentTimeMillis());

    return info;
  }

  @Autowired
  public void setUserService(UserService userService) {
    this.userService = userService;
  }
}
